<script setup>
import { getRolesWithUserPermission,allocateUserRoles } from '@/api/users';
import { ref } from 'vue';

const dialogFormVisible = ref(false);
const formLabelWidth = '140px';


const form = reactive({
    //接口需要的数据
    userId: undefined,
    roleIdList: [],
})

//保存所有角色信息
const allRoles = ref([]);

//封装显示的方法
const initAndShow = async (userId) => {
    dialogFormVisible.value = true;
    console.log(userId);
  const {data} =  await getRolesWithUserPermission(userId)
 if( data.code === '000000'){
    allRoles.value = data.data
    form.userId = userId;
    form.roleIdList =  data.data.filter( (r) => r.hasPermission).map(r => r.id)
    //过滤出有权限的角色  并且通过map方法把id提取出来
  
 } else {
    ElMessage.error('获取角色信息失败');
    throw new Error('获取角色信息失败');
 }
}
//把方法暴露出去
defineExpose({
    initAndShow,
})

//对话框表单提交事件
const onSubmit = async () => {
    const {data} = await allocateUserRoles(form.userId,form.roleIdList).finally(() => {
        dialogFormVisible.value = false;
    })
    if(data.code === '000000'){
        ElMessage.success('分配角色成功');
      } else {
        ElMessage.error('分配角色失败');
        throw new Error('分配角色失败');
      }
}     
</script>

<template>
 <el-dialog v-model="dialogFormVisible" title="分配角色" width="500">
    <el-form :model="form">
      
      <el-form-item label="" :label-width="formLabelWidth">
        <!-- hasRoleIds存储了用户已经拥有的角色id 直接选上 -->
        <el-select v-model="form.roleIdList" multiple placeholder="请选择角色">
          <el-option v-for = "role in allRoles" :key="role.id"   
          :label="role.name" :value="role.id" />
         
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
